<?php
namespace app\v1\controller;

use app\model\OrderItemModel;
use support\Request;
use support\Response;
use Exception;
use app\model\OrderModel;
use app\model\RefundRecordModel;
use app\model\PickUpPointModel;

class OrderController {

    public function getOrderList(Request $request){
        $user = $request->userLogin;
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $orderTab = $request->input('order_tab', 'all');
        $keyword = $request->input('keyword', '');
        $offset = ($page - 1) * $limit;

        $query = OrderModel::where('user_id', $user->id)->where('hide_at','=',0);

        if($orderTab == 'unpay'){
            $query->where('status','=',0);
        }else if($orderTab == 'un-send'){
            $query->where('status','=',1);
        }else if($orderTab == 'sent'){
            $query->where('status','=',2);
        }else if($orderTab == 'done'){
            $query->where('status','=',3);
        }else if($orderTab == 'refund'){
            $query->where('refund_status','=',2);
        }

        if(!empty($keyword)){
            // 通过OrderItemModel的goods_title关键词搜索匹配的订单
            $orderIds = OrderItemModel::where('goods_title', 'like', '%' . $keyword . '%')
                ->pluck('order_id')
                ->toArray();
            
            if (!empty($orderIds)) {
                $query->whereIn('id', $orderIds);
            } else {
                // 如果没有找到匹配的商品，返回空结果
                $query->where('id', 0);
            }
        }

        // 获取总数（应用所有筛选条件后）
        $total = $query->count();

        $orderList = $query->orderBy('created_at', 'desc')->offset($offset)->limit($limit)->get();
        $data = [];
        foreach($orderList as $o){
            $items = OrderItemModel::where('order_id', $o->id)->get();
            $arr = [
                'id' => $o->id,
                'trade_no' => $o->order_no,
                'status_text'=>$o->getStatusText(),
                'created_at' => date('Y-m-d H:i:s', $o->created_at),
                'items' => $items,
                'pay_amount' => round($o->pay_amount,2),
                'status' => $o->status,
                'refund_status' => $o->refund_status,
                'ping_id' => $o->ping_id,
                'express_type' => $o->express_type,
                'pick_up_point_id' => $o->pick_up_point_id,
            ];

            if($o->express_type == OrderModel::EXPRESS_TYPE_PICK_UP_POINT){
                $pickUpPoint = PickUpPointModel::find($o->pick_up_point_id);
                $arr['pick_up_point_name'] = $pickUpPoint->name;
            }

            $data[] = $arr;
        }    


        return json([
            'code' => 1,
            'msg' => '获取订单列表成功',
            'data' => [
                'list' => $data,
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'has_more' => ($page * $limit) < $total
            ]
        ]);
    }

    /**
     * 检查一个订单当前是否可以支付
     */
    public function checkCanPay(Request $request){
        $user = $request->userLogin;
        $orderId = $request->post('order_id');

        try {
            $order = OrderModel::where('id', $orderId)->where('user_id', $user->id)->first();
            if(!$order){
                throw new Exception('订单不存在');
            }

            if($order->status > 0){
                throw new Exception('订单状态不正确');
            }

            $order->order_no = null;
            $order->money = 0;
            $order->score = 0;
            $order->card_score = 0;
            $order->card_score_data = null;
            $order->updated_at = time();
            $order->update();

            return json(['code' => 1, 'data'=>null]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 订单详情
     */
    public function one(Request $request){
        $user = $request->userLogin;
        $orderId = $request->get('order_id');

        try {
            $order = OrderModel::where('id', $orderId)->where('user_id', $user->id)->first();
            if(!$order){
                throw new Exception('订单不存在');
            }

            $items = OrderItemModel::where('order_id', $order->id)->get();
            $itemListData = [];
            foreach($items as $item){
                $itemListData[] = [
                    'id' => $item->id,
                    'goods_title' => $item->goods_title,
                    'goods_image' => $item->goods_image,
                    'unit_price' => $item->unit_price,
                    'quantity' => $item->quantity,
                ];
            }

            // 退款信息
            $refund = RefundRecordModel::find($order->refund_record_id);
            if(!empty($refund)){
                $refund->status_txt = RefundRecordModel::STATUS_TEXT[$refund->status];
                $refund->created_at = date('Y-m-d H:i:s', $refund->created_at);
                $refund->refund_amount = round($refund->refund_amount,2);
            }

            $order->created_at = date('Y-m-d H:i:s', $order->created_at);
            $order->pay_time = date('Y-m-d H:i:s', $order->pay_time);

            $order['status_text'] = $order->getStatusText();

            return json(['code' => 1, 'data'=>[
                'order' => $order,
                'items' => $itemListData,
                'refund' => $refund
            ]]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(),'data'=>null]);
        }
    }

    /**
     * 订单退款
     */
    public function refund(Request $request){
        $user = $request->userLogin;
        $orderId = $request->post('order_id');
        $refundReason = $request->post('refund_reason');
        $phone = $request->post('phone');

        try {
            $order = OrderModel::where('id', $orderId)->where('user_id', $user->id)->first();
            if(!$order){
                throw new Exception('订单不存在');
            }

            $refundRecord = new RefundRecordModel();
            $refundRecord->type = 'order';
            $refundRecord->item_id = $order->id;
            $refundRecord->refund_amount = 0;
            $refundRecord->refund_at = 0;
            $refundRecord->status = 'doing';
            $refundRecord->created_at = time();
            $refundRecord->updated_at = time();
            $refundRecord->phone = $phone;
            $refundRecord->extra_data = json_encode([
                'refund_reason' => $refundReason
            ],256);
            $refundRecord->save();

            $order->refund_status = 1;
            $order->refund_record_id = $refundRecord->id;
            $order->refund_at = time();
            $order->update();

            return json(['code' => 1, 'data'=>null]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(),'data'=>null]);
        }
    }

    public function doHide(Request $request){
        $user = $request->userLogin;
        $id = $request->post('id');

        try {
            $order = OrderModel::where('id', $id)->where('user_id', $user->id)->first();
            if(!$order){
                throw new Exception('订单不存在');
            }

            $order->hide_at = time();
            $order->update();

            return json(['code' => 1, 'data'=>null]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(),'data'=>null]);
        }
    }

    /**
     * 更新订单快递单号
     */
    public function updateExpressNo(Request $request){
        $user = $request->userLogin;
        $orderId = $request->post('order_id');
        $expressNo = $request->post('express_no');

        try {
            $order = OrderModel::where('id', $orderId)->where('user_id', $user->id)->first();
            if(!$order){
                throw new Exception('订单不存在');
            }

            // 检查订单状态，只有已付款的订单才能发货
            if($order->status != 1){
                throw new Exception('订单状态不正确，只有已付款的订单才能发货');
            }

            // 检查快递单号是否为空
            if(empty($expressNo)){
                throw new Exception('快递单号不能为空');
            }

            if($user->is_store_worker != 1){
                throw new Exception('您不是配货员，不能发货');
            }

            if($order->express_type == OrderModel::EXPRESS_TYPE_PICK_UP_POINT){
                throw new Exception('自提点订单不能发货');
            }

            // 更新订单信息
            $order->status = 2; // 已发货
            $order->delivery_status = 1; // 已发货
            $order->delivery_time = time(); // 发货时间
            $order->express_no = $expressNo; // 快递单号
            $order->express_send_user_id = $user->id; // 发货人ID
            $order->updated_at = time();
            $order->update();

            return json(['code' => 1, 'msg' => '发货成功', 'data'=>null]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(),'data'=>null]);
        }
    }

} 